#!/usr/bin/env python 
# -*- coding: utf-8 -*-

import os
import zipfile

import xmltodict

from axmlparserpy import axmlprinter
from xml.dom import minidom
import datetime


def get_apk_list(dir, topdown=True):
    """ 获取指定目录下的apk文件列表"""
    apk_list = []
    if os.path.isdir(dir):
        for root, dirs, files in os.walk(dir, topdown):
            """os.walk(path),遍历path，返回一个对象，他的每个部分都是一个三元组,('目录x'，[目录x下的目录list]，目录x下面的文件)"""
            for name in files:
                if name.endswith(".apk"):
                    # 包名格式固定例如：wxdzz-0.1.1.1-b-n-20170711091351.apk
                    up_time = name[-18:-4]
                    try:
                        up_time = int(up_time)
                        # 获取最近8天的包
                        if up_time >= int((
                                    datetime.datetime.now() - datetime.timedelta(
                                    days=1024)).strftime(
                            "%Y%m%d%H%M%S")):
                            apk_list.append(os.path.join(root, name))
                    except ValueError as e:
                        pass

    else:
        print(dir + "is not exists")
    apk_list.sort()
    apk_list.reverse()
    return apk_list


def unzip_apk(apk_path):
    """解压apk中的AndroidManifest.xml"""
    AndroidManifest = None
    try:
        with zipfile.ZipFile(apk_path) as zipFile:
            AndroidManifest = zipFile.extract("AndroidManifest.xml",os.path.dirname(apk_path))
    except FileNotFoundError as e:
        print(e)
    except Exception as e:
        print(e)
    return AndroidManifest


def parser_manifest(xml_path):
    """ 解析AndroidManifest.xml,返回apk包信息字典apk_info"""
    buff = None
    apk_info = {}
    try:
        with open(xml_path, 'rb') as xml_file:
            ap = axmlprinter.AXMLPrinter(xml_file.read())
            buff = minidom.parseString(ap.getBuff()).toxml()
    except FileNotFoundError as e:
        print(e)
    except Exception as e:
        print(e)
    elem_dict = xmltodict.parse(buff, attr_prefix="", cdata_key="")
    manifest_dict = elem_dict.get("manifest")
    for key, value in manifest_dict.items():
        if key == "package": apk_info["package"] = value
        if key == "android:versionCode": apk_info["versionCode"] = value
        if key == "android:versionName": apk_info["versionName"] = value
    meta_data = manifest_dict.get("application").get("meta-data")
    for app in meta_data:
        # print(app)
        for k, v in app.items():
            if v == "com.ssjj.fnsdk.PLAT_CHANNEL":
                apk_info["PLAT_CHANNEL"] = app.get('android:value')
            if v == "com.ssjjsy.channelId":
                apk_info["channelId"] = app.get('android:value')
            if v == "com.ssjj.fnsdk.FNPID":
                apk_info["FNPID"] = app.get('android:value')
            if v == "com.ssjjsy.channelId":
                apk_info["channelId"] = app.get('android:value')
    return apk_info


def get_apk_md5(apk_file):
    """ 计算apk包的md5值"""
    ret_md5 = None
    from hashlib import md5
    m = md5()
    try:
        with open(apk_file, "rb") as a_file:
            m.update(a_file.read())
            ret_md5 = m.hexdigest()
    except FileNotFoundError as e:
        print(e)
    except Exception as e:
        print(e)
    return ret_md5


if __name__ == '__main__':
    apk_path = r'C:\pkg\大陆游戏包'
    print(get_apk_list(apk_path))
    apk_file = r'C:\pkg\大陆游戏包\yqqs-0.1.1.1-b-n-20210725071351.apk'
    # print(unzip_apk(apk_file))
    # xml_file = r'D:\pkg2\AndroidManifest.xml'
    print(parser_manifest(unzip_apk(apk_file)))
    # apk_file = r'C:\pkg\大陆游戏包\yqqs-3.2.3-b-n-112.apk'
    # print(get_apk_md5(apk_file))
